import 'package:edu/constants/app_icons.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/main_tab/acount/acount_page_logic.dart';
import 'package:edu/pages/common/account_avatar_widget.dart';
import 'package:edu/utils/app_router.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class AcountPage extends StatefulWidget {
  const AcountPage({super.key});

  @override
  State<AcountPage> createState() => _AcountPageState();
}

class _AcountPageState extends State<AcountPage> {
  @override
  void initState() {
    super.initState();

    context.read<AcountPageLogic>().init();
  }

  // 构建页面
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20),
        child: ScrollConfiguration(
          // 关闭滚动条
          behavior: const ScrollBehavior().copyWith(scrollbars: false),
          child: ListView(
            children: [
              // 登录
              const SizedBox(height: 10),
              _buildPageHeader(context),
              // 第一部分
              const SizedBox(height: 30),
              _buildFirstSection(),
              // 第二部分
              const SizedBox(height: 20),
              _buildSecondSection(),
              // 退出登录
              _buildLogout(context),
              // 底部说明
              const SizedBox(height: 10),
              const _Footer(),
            ],
          ),
        ),
      ),
    );
  }

  // 构建第一行cart
  Widget _buildFirstSection() {
    final logic = context.read<AcountPageLogic>();
    const divider = Divider(
      height: 0.5,
      indent: 50,
      endIndent: 15,
      color: Colors.grey,
    );

    return Card(
      child: Column(
        children: [
          // 购物车
          _ListViewCell(
            icon: Icons.shopping_cart_outlined,
            title: AppStrings.shoppingCart,
            onTap: () {
              if (logic.isLogin == false) {
                context.pushNamed(AppRouter.kLogin);
              }
              context.pushNamed(AppRouter.kShoppingCart);
            },
          ),
          divider,
          // 我的订单
          _ListViewCell(
            icon: Icons.assessment,
            title: AppStrings.myOrder,
            onTap: () {
              if (logic.isLogin == false) {
                context.pushNamed(AppRouter.kLogin);
              }
            },
          ),
          divider,
          // 收藏课程
          _ListViewCell(
            icon: Icons.favorite,
            title: AppStrings.favoriteCourse,
            onTap: () {
              if (logic.isLogin == false) {
                context.pushNamed(AppRouter.kLogin);
              }
            },
          ),
        ],
      ),
    );
  }

  // 构建第二部分cart
  Widget _buildSecondSection() {
    final logic = context.read<AcountPageLogic>();
    const divider = Divider(
      height: 0.5,
      indent: 50,
      endIndent: 15,
      color: Colors.grey,
    );

    return Card(
      child: Column(
        children: [
          // 关于学习
          _ListViewCell(
            icon: Icons.info,
            title: AppStrings.aboutLearning,
            onTap: () {
              if (logic.isLogin == false) {
                context.pushNamed(AppRouter.kLogin);
              }
            },
          ),
          divider,
          // 欢迎页
          _ListViewCell(
            icon: Icons.support_outlined,
            title: AppStrings.welcomePage,
            onTap: () {
              if (logic.isLogin == false) {
                context.pushNamed(AppRouter.kLogin);
              }
            },
          ),
          divider,
          // 评分
          _ListViewCell(
            icon: Icons.star_rate,
            title: AppStrings.ratingMe,
            onTap: () {
              if (logic.isLogin == false) {
                context.pushNamed(AppRouter.kLogin);
              }
            },
          ),
          divider,
          // 编辑资料
          _ListViewCell(
            icon: Icons.edit,
            title: AppStrings.editProfile,
            onTap: () {
              if (logic.isLogin) {
                context.pushNamed(AppRouter.kAccountProfileSetting);
              } else {
                context.pushNamed(AppRouter.kLogin);
              }
            },
          ),
        ],
      ),
    );
  }

  // 退出登录
  Widget _buildLogout(BuildContext context) {
    return Selector<AcountPageLogic, bool>(
      selector: (context, logic) => logic.isLogin,
      builder: (context, isLogin, child) {
        if (isLogin) {
          return Column(
            children: [
              const SizedBox(height: 20),
              Card(
                child: _ListViewCell(
                  icon: Icons.exit_to_app,
                  title: AppStrings.logout,
                  onTap: () {
                    context.read<AcountPageLogic>().logout();
                  },
                ),
              ),
            ],
          );
        } else {
          // 不显示退出按钮
          return const SizedBox.shrink();
        }
      },
    );
  }

  // 根据用户登录状态展示不同的页面
  Widget _buildPageHeader(BuildContext context) {
    return Selector<AcountPageLogic, bool>(
      selector: (context, logic) => logic.isLogin,
      builder: (context, v, child) {
        if (v) {
          // 登录成功,显示brief信息
          return const _BriefProfileHeader();
        } else {
          // 登录失败,显示登录按钮
          return const _NoneLoginHeader();
        }
      },
    );
  }
}

//用于创建列表中的单个单元格
class _ListViewCell extends StatelessWidget {
  final IconData icon;
  final String title;
  final GestureTapCallback onTap;

  const _ListViewCell({
    required this.icon,
    required this.title,
    required this.onTap,
  });

  // 构建可点击的列表项
  @override
  Widget build(BuildContext context) {
    final style = Theme.of(
      context,
    ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600, fontSize: 16);
    return InkWell(
      onTap: onTap,
      child: ListTile(
        leading: Icon(
          icon,
          color: Theme.of(context).textTheme.titleLarge?.color,
          size: 20,
        ),
        trailing: const Icon(Icons.arrow_forward_ios, size: 16),
        title: Text(title, style: style),
        onTap: null,
      ),
    );
  }
}

// 用于显示未登录状态的头部区域
class _NoneLoginHeader extends StatelessWidget {
  const _NoneLoginHeader();

  // 构建可点击的登录页面
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        context.pushNamed(AppRouter.kLogin);
      },
      child: Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        child: Row(
          children: [
            SizedBox(
              height: 60,
              width: 60,
              child: CircleAvatar(
                radius: 30,
                backgroundColor: Theme.of(context).colorScheme.surface,
                child: ColorFiltered(
                  colorFilter: ColorFilter.mode(
                    Colors.grey[600]!,
                    BlendMode.srcIn,
                  ),
                  child: Image.asset(AppIcons.greyAvatar),
                ),
              ),
            ),
            const SizedBox(width: 16),
            // 创建一个垂直排列的文本区域，包含标题和副标题
            SizedBox(
              height: 60,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    AppStrings.clickLogin,
                    style: Theme.of(context).textTheme.headlineSmall,
                  ),
                  const SizedBox(height: 5),
                  Text(
                    AppStrings.welcomeLogin,
                    style: Theme.of(
                      context,
                    ).textTheme.bodyMedium?.copyWith(color: Colors.grey),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 底部说明
class _Footer extends StatelessWidget {
  const _Footer();

  @override
  Widget build(BuildContext context) {
    final style = Theme.of(
      context,
    ).textTheme.bodySmall?.copyWith(color: Colors.grey);

    return Column(
      children: [
        Text('www.wzplove.com', style: style),
        const SizedBox(height: 2),
        Text(AppStrings.profileFooter, style: style),
        const SizedBox(height: 10),
      ],
    );
  }
}

class _BriefProfileHeader extends StatelessWidget {
  const _BriefProfileHeader();

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).scaffoldBackgroundColor,
      child: Row(
        children: [
          _buildUserAvatar(context),
          const SizedBox(width: 16),
          _buildUserTextInfo(context),
        ],
      ),
    );
  }

  //构建用户头像
  Widget _buildUserAvatar(BuildContext context) {
    return const SizedBox(
      height: 60,
      width: 60,
      child: ClipOval(child: AccountAvatarWidget()),
    );
  }

  // 用户昵称
  Widget _buildUserTextInfo(BuildContext context) {
    return SizedBox(
      height: 60,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Selector<AcountPageLogic, String?>(
                selector: (context, logic) => logic.nickName,
                builder: (context, v, child) {
                  return Text(
                    v ?? '',
                    style: Theme.of(context).textTheme.headlineSmall,
                  );
                },
              ),
              const SizedBox(width: 5),
              _buildGenderImage(context),
            ],
          ),
          const SizedBox(height: 5),
          Row(
            children: [
              // 累计学习天数
              _buildEduDaysText(context),
              const SizedBox(width: 10),
              // 累计学习时长
              _buildEduMinutesText(context),
            ],
          ),
        ],
      ),
    );
  }

  // 性别
  Widget _buildGenderImage(BuildContext context) {
    return Selector<AcountPageLogic, String?>(
      selector: (context, logic) => logic.gender,
      builder: (context, v, child) {
        if (v != null) {
          final icon = v == 'm' ? Icons.male : Icons.female;
          return ClipOval(
            child: Container(
              height: 20,
              width: 20,
              color: Theme.of(
                context,
              ).colorScheme.surface.withValues(alpha: 0.75),
              child: Center(
                child: Icon(
                  icon,
                  size: 16,
                  color: Theme.of(context).colorScheme.primary,
                ),
              ),
            ),
          );
        } else {
          return const SizedBox.shrink();
        }
      },
    );
  }

  // 用户学习天数
  Widget _buildEduDaysText(BuildContext context) {
    // 获取当前主题
    final isDartMode = AppTheme.shared.isDark;
    // 获取正常颜色
    final normalColor = isDartMode ? Colors.grey[300] : Colors.grey[700];
    // 获取高亮颜色
    final normalStyle = Theme.of(
      context,
    ).textTheme.bodyMedium?.copyWith(color: normalColor);
    // 获取粗体样式
    final boldStyle = Theme.of(
      context,
    ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600);
    // 创建文本
    final eduDays = TextSpan(text: AppStrings.eduDays, style: normalStyle);
    final day = TextSpan(text: AppStrings.day, style: normalStyle);

    return Selector<AcountPageLogic, int?>(
      selector: (context, logic) => logic.eduDays,
      builder: (context, v, child) {
        final span = TextSpan(text: '${v ?? 0}', style: boldStyle);
        return RichText(text: TextSpan(children: [eduDays, span, day]));
      },
    );
  }

  // 总时长
  Widget _buildEduMinutesText(BuildContext context) {
    // 获取当前主题
    final isDartMode = AppTheme.shared.isDark;
    // 获取正常颜色
    final normalColor = isDartMode ? Colors.grey[300] : Colors.grey[700];
    // 获取高亮颜色
    final normalStyle = Theme.of(
      context,
    ).textTheme.bodyMedium?.copyWith(color: normalColor);
    // 获取粗体样式
    final boldStyle = Theme.of(
      context,
    ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600);
    // 创建文本
    final eduMinutes = TextSpan(
      text: AppStrings.eduMinutes,
      style: normalStyle,
    );

    return Selector<AcountPageLogic, int>(
      selector: (context, logic) => logic.eduMinutes,
      builder: (context, v, child) {
        TextSpan span1, span2;
        if (v / 60 < 1) {
          span1 = TextSpan(text: '${v ~/ 60}', style: boldStyle);
          span2 = TextSpan(text: AppStrings.hour, style: normalStyle);
        } else {
          span1 = TextSpan(text: '$v', style: boldStyle);
          span2 = TextSpan(text: AppStrings.minute, style: normalStyle);
        }
        return RichText(text: TextSpan(children: [eduMinutes, span1, span2]));
      },
    );
  }
}
